package edu.gdkm.ssm.service.impl;

import edu.gdkm.ssm.dao.IUserDao;
import edu.gdkm.ssm.domain.Role;
import edu.gdkm.ssm.domain.UserInfo;
import edu.gdkm.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service("userService") //与spring-security.xml配置文件<security:authentication-manager>相对应
@Transactional // 开始spring事务管理，出现异常会自动事务回滚
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        try{
            userInfo = userDao.findByUserName(username);
        }catch (Exception e){
            e.printStackTrace();
        }
        // 处理自己的用户对象封装成UserDetails
        User user = new User(userInfo.getUsername(),  // 应用内唯一的用户名
                userInfo.getPassword(),     // 用户的加密后的密码bCryptPasswordEncoder.encode(userInfo.getPassword())， 不加密会使用{noop}前缀
                userInfo.getStatus() == 0 ? false : true,
                true, 
                true, 
                true, 
                getAuthority(userInfo.getRoles()));  // 用户的权限集， 默认需要添加ROLE_ 前缀
        return user;
    }

    /**
     * 作用就是返回一个List集合，集合中装入的是角色描述
     * @param roles
     * @return
     */
    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> list = roles.stream()
                .map(role -> {return new SimpleGrantedAuthority("ROLE_" + role.getRoleName());})
                .collect(Collectors.toList());
        return list;
    }

    @Override
    public List<UserInfo> findAll() throws Exception {
        return this.userDao.findAll();
    }

    @Override
    public void save(UserInfo userInfo) throws Exception {
        if(userInfo != null && this.userDao.findByUserName(userInfo.getUsername()) == null){
            userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
            this.userDao.save(userInfo);
        }
    }

    @Override
    public UserInfo findById(String id) throws Exception{
        return this.userDao.findById(id);
    }

    @Override
    public void addRoleToUser(String userId, String[] roleIds) {
        for(String roleId : roleIds){
            this.userDao.addRoleToUser(userId, roleId);
        }
    }
}
